import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Test_4_19 {
    /*public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        //  you-->两分    oo-->一分      除去构成you的o,剩下的有n个o,就有(n-1)分
        // 询问次数
        int q = in.nextInt();
        //拼接数组
        StringBuilder str = new StringBuilder();
        int[] y =new int[q];//y的个数
        int[] o =new int[q];//o的个数
        int[] u = new int[q];//u的个数
        //输入个数
        for (int i = 0; i < q; i++) {
            y[i] = in.nextInt();
            o[i] = in.nextInt();
            u[i] = in.nextInt();
        }
        for (int i = 0; i < q; i++) {
            int flag = Math.min(y[i],o[i]);
            int flag2 = Math.min(flag,u[i]);//得出每一次能构成'you'的最大个数
            //剩下字数
            y[i]-=flag2;
            o[i]-=flag2;
            u[i]-=flag2;
            int sum = 0;//分数的总和
            if(o[i]==0){
                sum = flag2*2;
            }else{
                sum = flag2*2+(o[i]-1);
            }
            System.out.println(sum);
        }
    }*/


    /*public int LastRemaining_Solution (int n, int m) {
        if(n==0||m==0){
            //没有小朋友
            return -1;
        }
        return getChild(n,m);
    }
    public static int getChild(int n,int m){
        if(n==1){
            //证明只有一个小朋友
            return 0;
        }
        int a = getChild(n-1,m);
        return (m+a)%n;
    }*/


    public int rotApple (ArrayList<ArrayList<Integer>> grid) {
        int n = grid.size();
        int m = grid.get(0).size();

        Queue<Integer> queue = new LinkedList<>();

        int apple = 0;//没有腐烂的个数
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if(grid.get(i).get(j)==2){
                    queue.add(i*m+j);
                }
                if(grid.get(i).get(j)==1){
                    apple++;
                }
            }
        }


        int[] arr1 = {-1,1,0,0};
        int[] arr2 = {0,0,-1,1};
        int deep=0;
        int appleBad = 0;//已经烂掉的苹果
        while(!queue.isEmpty()){
            int size = queue.size();
            for(int i=0;i<size;i++){
                int xy = queue.poll();
                int x1 = xy/m;
                int y1 = xy%m;

                for (int j = 0; j < 4; j++) {
                    int x2 = x1+arr1[j];
                    int y2 = y1+arr2[j];

                    if(x2>=0&&x2<n&&y2>=0&&y2<m&&grid.get(x2).get(y2)==1){
                        queue.add(x2*m+y2);
                        appleBad++;
                        grid.get(x2).set(y2,2);
                    }
                }
            }
            deep++;
        }
        if(appleBad!=apple){
            return -1;
        }
        return deep-1;
    }
}
